import { getUserInfo } from '@/api/user'

export default {
  namespaced: true,
  state: {
    roles: [],
    avatar: null,
    username: null,
    menuRoutes: null,
    cachePool: []
  },
  getters: {
    roles: state => state.roles,
    avatar: state => state.avatar,
    username: state => state.username,
    menuRoutes: state => state.menuRoutes,
    cachePool: state => state.cachePool
  },
  mutations: {
    setRoles(state, roles) {
      state.roles = roles
    },
    setAvatar(state, avatar) {
      state.avatar = avatar
    },
    setUsername(state, username) {
      state.username = username
    },
    setMenuRoutes(state, menuRoutes) {
      state.menuRoutes = menuRoutes
    },
    setCachePool(state, cachePool) {
      state.cachePool = cachePool
    }
  },
  actions: {
    /**
     * 获取用户相关信息
     */
    getUserInfo({ commit }) {
      return new Promise((resolve, reject) => {
        try {
          getUserInfo()
            .then(res => {
              if (res.result) {
                commit('setRoles', res.data.role)
                commit(
                  'setAvatar',
                  'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.zhimg.com%2F50%2Fv2-b8f57a87ccff572c84bea1c0497f999d_r.jpg&refer=http%3A%2F%2Fpic1.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1638543817&t=c024f90fce20e7492dd2f804c5d8c207'
                )
                commit('setUsername', res.data.user_name)
                resolve(res.data)
              } else {
                reject(res)
              }
            })
            .catch(err => {
              reject(err)
            })
        } catch (error) {
          reject(error)
        }
      })
    }
  }
}
